package com.seqb.common.task;

import cn.hutool.extra.mail.MailUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.seqb.common.config.RedisConfig;
import com.seqb.common.utils.RedisUtils;
import com.seqb.utils.DateUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lilinshen
 * @title 太阳城每天签到定时任务
 * @description 请填写相关描述
 * @date 2020/11/20
 */
public class TaiyangchengJob implements Job {
    private static final Logger LOGGER = LoggerFactory.getLogger(TaiyangchengJob.class);
    public HttpHeaders headers = new HttpHeaders();
    @Autowired
    private RedisUtils redisUtils;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        try {
            headers = new HttpHeaders();
            Object taskParams = redisUtils.get("taskParams");
            if (null != taskParams) {
                JSONArray parseArray = JSON.parseArray(taskParams.toString());
                for (int i = 0; i < parseArray.size(); i++) {
                    JSONObject item = parseArray.getJSONObject(i);
                    String type = item.getString("type");
                    if ("TaiyangchengJob".equals(type)) {
                        JSONArray value = item.getJSONArray("value");
                        for (int j = 0; j < value.size(); j++) {
                            JSONObject jsonObject = value.getJSONObject(j);
                            headers.add(jsonObject.getString("key"), jsonObject.getString("value"));
                        }
                    }
                }
            }
            LOGGER.info("太阳城每天签到定时任务开始-----------" + DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            SignInDaily();
            LOGGER.info("太阳城每天签到定时任务结束-----------" + DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 太阳城每天签到领取积分
     *
     * @return
     */
    private void SignInDaily() {

        //记录是否失效
        boolean flag = true;
        Object flagRedis = redisUtils.get(RedisConfig.COM_PREFIX + this.getClass().getSimpleName());
        try {
            RestTemplate restTemplate = new RestTemplate();
            String requestUrl = "https://www.ptweixin.com/api/b804cba681/user/?do_action=user.sign";
            HttpMethod httpMethod = HttpMethod.GET;
            Map<String, Object> paramsMap = new HashMap<>();
            HttpEntity httpEntity = new HttpEntity(paramsMap, headers);
            ResponseEntity<String> responseEntity = restTemplate.exchange(requestUrl, httpMethod, httpEntity, String.class);
            HttpStatus status = responseEntity.getStatusCode();
            if (status.equals(HttpStatus.OK)) {
                String entityBody = responseEntity.getBody();
                //{"msg":"您今天已经签到了！","ret":0}
                //{"msg":"您还没登录，请先登录！","ret":0}
                try {
                    JSONObject parse = (JSONObject) JSON.parse(entityBody);
                    if (parse.containsKey("msg")) {
                        String msg = parse.getString("msg");
                        if (msg.indexOf("登录") > 0) {
                            flag = false;
                        }
                    } else {
                        flag = false;
                    }
                } catch (Exception e) {
                    flag = false;
                }
            }
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }
        if (!flag) {
            LOGGER.info("太阳城定时任务，执行失败。");
        } else {
            LOGGER.info("太阳城定时任务，执行成功。");
        }
        if (!flag && null == flagRedis) {
            //设置一天失效时间的key，每天只发一次邮件通知
            redisUtils.set(RedisConfig.COM_PREFIX + this.getClass().getSimpleName(), true, 86400);
            //发送邮件通知唯佳生活签到失效
            MailUtil.send("lilinshen@cecjx.com", "太阳城定时任务", "太阳城定时任务，用户cookie失效，请及时更新用户cookie信息。", false);
        }
    }

}
